package cn.edu.cug.cs.gtl.plugins.h3dfile.layer;

import cn.edu.cug.cs.gtl.api.wrapper.GeometryWrapper;
import cn.edu.cug.cs.gtl.api.wrapper.geometry3d.VolumeModelWrapper;
import cn.edu.cug.cs.gtl.api.wrapper.geometry3d.VoxelModelWrapper;
import cn.edu.cug.cs.gtl.apis.render.nodes.Group;
import cn.edu.cug.cs.gtl.apis.render.nodes.Node;
import cn.edu.cug.cs.gtl.apis.ui.AbstractApplication;
import cn.edu.cug.cs.gtl.apis.ui.actions.AbstractAction;
import cn.edu.cug.cs.gtl.common.Pair;
import cn.edu.cug.cs.gtl.protos.*;
import com.google.protobuf.Any;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.Locale;
import java.util.ResourceBundle;

public class ImportVolFileAction extends AbstractAction {

    @Override
    public void initialize(AbstractApplication theApp) {
        ResourceBundle resourceBundle = ResourceBundle.getBundle("h3dfile_resource", Locale.getDefault());

        name=resourceBundle.getString("popupmenu.model3d.layer.import_vol_file");
        menuItem.setText(name);


        this.theApp = theApp;
        menuItem.addActionListener(this);
        JPopupMenu popupMenu = theApp.getMainFrame()
                .getProjectPanel()
                .getTreeComponent()
                .getLayerNodePopupMenu();
        popupMenu.add(menuItem);
    }

    /**
     * Invoked when an action occurs.
     *
     * @param e the event to be processed
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        final JFileChooser volFileChooser = new JFileChooser(new File(System.getProperty("user.dir")) );
        volFileChooser.setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                if ( f == null )
                    return false;
                if ( f.isDirectory() )
                    return true;
                return f.getName().toLowerCase().endsWith(".vol");
            }

            @Override
            public String getDescription() {
                return "VOL File";
            }
        });

        volFileChooser.removeChoosableFileFilter(volFileChooser.getAcceptAllFileFilter());

        if ( volFileChooser.showOpenDialog(null) != JFileChooser.APPROVE_OPTION )
            return;


        String fileName = volFileChooser.getSelectedFile().getAbsolutePath();
        VoxelModelWrapper vmw = new VoxelModelWrapper(new VolumeModelWrapper.VolFileReader(fileName));
        VoxelModel voxelModel = vmw.get();
        Geometry geometry = GeometryWrapper.pack(voxelModel);

        try {
            Project project = theApp.getProject();
            Project.Builder pb = Project.newBuilder(project);
            Map map = theApp.getCurrentMap();
            int mapIndex=0,layerIndex=0;
            Layer layer = theApp.getCurrentLayer();

            int mapCount = pb.getMapCount();
            for(int i=0;i<mapCount;++i){
                Map.Builder mapBuilder = pb.getMapBuilder(i);
                int layerCount = mapBuilder.getLayerCount();
                mapIndex = i;
                for(int j=0;j<layerCount;++j){
                    Layer.Builder layerBuilder = mapBuilder.getLayerBuilder(j);
                    layerIndex = j;
                    if(layer!=null && layer.getName().equals(layerBuilder.getName())){

                        Table.Builder tableBuilder = layerBuilder.getAttributeTableBuilder();
                        tableBuilder.getInfoBuilder()
                                .addColumnInfo(
                                        ColumnInfo.newBuilder()
                                                .setName("ID")
                                                .setType(Type.newBuilder().setId(Type.EnumType.INTEGER))
                                                .build())
                                .addColumnInfo(
                                ColumnInfo.newBuilder()
                                        .setName("NAME")
                                        .setType(Type.newBuilder().setId(Type.EnumType.TEXT))
                                        .build());
                        tableBuilder.addTuple(
                                Tuple.newBuilder()
                                        .addElement(Any.pack(IntegerValue.newBuilder().setValue(10).build()))
                                        .addElement(Any.pack(TextValue.newBuilder().setValue(new cn.edu.cug.cs.gtl.io.File(fileName).getFileNameWithoutSuffix()).build())).build());

                        layerBuilder.addGeometry(geometry);

                        break;
                    }
                }
            }
            project = pb.build();
            theApp.refreshAll(project);
        }
        catch (Exception exception){
            exception.printStackTrace();
        }
    }
}
